// lib/models/address.dart
import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';

/// 0/1/true/false/"1"/"0" ↔ bool（序列化输出 0/1）
class BoolIntConverter implements JsonConverter<bool, Object?> {
  const BoolIntConverter();
  @override
  bool fromJson(Object? json) {
    if (json is bool) return json;
    if (json is num) return json != 0;
    if (json is String) {
      final s = json.trim().toLowerCase();
      return s == '1' || s == 'true' || s == 'yes';
    }
    return false;
  }

  @override
  int toJson(bool v) => v ? 1 : 0; // 后端需要 0/1
}

@JsonSerializable()
class Address {
  final int? id; // 地址ID
  final int? userId; // 所属用户ID
  final String receiverName; // 收货人姓名

  @JsonKey(name: 'receiverPhone')
  final String receiverPhone; // 收货人手机号

  final String province; // 省份
  final String city; // 城市
  final String district; // 区/县
  final String detailAddress; // 详细地址
  final String postalCode; // 邮编

  @BoolIntConverter()
  bool isDefault; // 是否默认（0/1 与 bool 互转）

  Address({
    this.id,
    this.userId,
    required this.receiverName,
    required this.receiverPhone,
    required this.province,
    required this.city,
    required this.district,
    required this.detailAddress,
    required this.postalCode,
    required this.isDefault,
  });

  factory Address.fromJson(Map<String, dynamic> json) =>
      _$AddressFromJson(json);
  Map<String, dynamic> toJson() => _$AddressToJson(this);
}
